<?php
namespace Org\Util;
use Think\Model;
use Think\Page;
/**
 * Created by PhpStorm.
 * User: Eugene
 * Date: 2016/1/12
 * Time: 10:23
 */
class DBUtil
{

    public static function getPageList($page=1,$r=10,$sql){
        $model = new Model();
        $count = $model->query("select count(1) AS counts from ( $sql ) A");
        $sql .= " limit ".$r*($page-1).",$r";
        $list = $model->query($sql);
        $page = new Page($count[0]["counts"],$r);
        $result["page"] = $page;
        $result["data"] = $list;
        return $result;
    }

    public static function detail($sql,$id){
        $model = new Model();
        $result = $model->query($sql,$id);
        return $result[0];
    }

    public static function save($db,$prefix,$data){
        $model = new Model($db,$prefix);
        $id = $model->data(array_filter($data,function($value){
            if(trim($value)!=""&$value!=null){
                return true;
            }
            return false;
        }))->add();
        if ($id!==false) {
            $result["id"] = $id;
            $result["info"] = "新增成功";
            $result["status"] = "1";
        } else {
            $result["info"] = "新增失败";
            $result["status"] = "0";
        }
        return $result;
    }

    public static function update($db,$prefix,$data){
        $model = new Model($db,$prefix);
        if ($model->save($data)>=0) {
            $result["info"] = "修改成功";
            $result["status"] = "1";
        } else {
            $result["info"] = "修改失败";
            $result["status"] = "0";
        }
        return $result;
    }

    public static function delete($db,$prefix,$id){
        $model = new Model($db,$prefix);
        if ($model->delete($id)!==false) {
            $result["info"] = "删除成功";
            $result["status"] = "1";
        } else {
            $result["info"] = "删除失败";
            $result["status"] = "0";
        }
        return $result;
    }
}